package Chat

import (
	"sanguo/cluster"
	codecs "sanguo/codec/cs"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	cs_message "sanguo/protocol/cs/message"
	ss_msg "sanguo/protocol/ss/message"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionChat struct {
	transaction.TransactionBase
	user *user.User
	req  *codecs.Message
}

func (this *transactionChat) GetModuleName() string {
	return "Chat"
}

func (this *transactionChat) GetReplyMsg() proto.Message {
	return nil
}

func (this *transactionChat) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionChat) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionChat) Begin() {
	defer this.user.EndTrans(this)

	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	r := roleModule.CurrentRole()
	if nil == r || !r.IsRoleModleData() {
		return
	} else {
		if r.NodeChat == nil {
			return
		} else {
			msg := this.req.GetData().(*cs_message.ChatToS)
			arg := &ss_msg.Chat{
				UserID:   proto.String(r.GetUserID()),
				RoleID:   proto.Uint64(r.GetID()),
				Content:  proto.String(msg.GetContent()),
				Type:     proto.Int32(msg.GetType()),
				ToRoleID: proto.Uint64(msg.GetToRoleID()),
			}
			//node_game.Infoln("Chat Msg :", arg)

			cluster.PostMessage(*r.NodeChat, arg)
		}
	}
}

func (this *transactionChat) End() {
}

func (this *transactionChat) Timeout() {
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.ChatToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionChat{
			user: user,
			req:  msg,
		}
	})
}
